package cc.shacocloud.kotlin.tools.cli

import cc.shacocloud.kotlin.tools.uitls.AppUtil
import cc.shacocloud.kotlin.tools.uitls.Utils.getDefaultClassLoader
import java.io.File
import java.io.FileNotFoundException
import java.io.FileOutputStream
import java.nio.file.Paths
import java.util.zip.ZipEntry
import java.util.zip.ZipFile
import kotlin.io.path.absolutePathString

/**
 *
 * @author 思追(shaco)
 */
object Utils {

    /**
     * 主文件目录
     */
    val homeDir = Paths.get(AppUtil.getStartDir(Utils::class.java).absolutePath, "workspace").absolutePathString()

    /**
     * copy jar下的指定资源
     */
    fun copyResourcesJar(
        classPath: String,
        fileName: String,
        outHomeDir: File
    ): File {
        val result = File(outHomeDir, fileName)

        val classLoader = getDefaultClassLoader()
        val url =
            if (classLoader != null) classLoader.getResource(classPath) else ClassLoader.getSystemResource(classPath)
        if (url == null) {
            throw FileNotFoundException("类路径资源 [$classPath] 无法解析为 URL，因为它不存在")
        }

        url.openStream().use { input ->

            if (!result.exists()) {
                result.parentFile?.mkdirs()
                result.createNewFile()
            }

            FileOutputStream(result).use { output ->
                input.transferTo(output)
            }
        }
        return result.absoluteFile
    }

    /**
     * zip 文件解压
     * @param descDir 目标文件夹
     */
    fun File.unzip(descDir: File) {
        val targetDir = descDir.absolutePath

        ZipFile(this).use { zf ->
            val entries = zf.entries()
            while (entries.hasMoreElements()) {
                val zipEntry: ZipEntry = entries.nextElement() as ZipEntry
                val zipEntryName: String = zipEntry.name

                zf.getInputStream(zipEntry).use { input ->
                    val targetFile = Paths.get(targetDir, zipEntryName).toFile()

                    targetFile.delete()
                    targetFile.parentFile?.mkdirs()
                    targetFile.createNewFile()

                    FileOutputStream(targetFile).use { output ->
                        input.transferTo(output)
                    }
                }
            }
        }
    }

}